package com.nsgf.library.ui.page;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.response.DataResult;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityNsgfMessageBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.event.EventMsg;
import com.nsgf.library.event.RxBus;
import com.nsgf.library.magicindicator.buildins.commonnavigator.CommonNavigator;
import com.nsgf.library.magicindicator.buildins.commonnavigator.titles.badge.BadgePagerTitleView;
import com.nsgf.library.ui.adapter.XFragmentAdapter;
import com.nsgf.library.ui.page.fragment.MessageFragment;
import com.nsgf.library.utils.PublicMethodUtils;
import com.nsgf.library.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

public class MessageActivity extends BaseActivity {

    MessageStates states;

    private List<Fragment> fragmentList = new ArrayList<>();

    private String[] mPageTitleList;
    private AccountRequester mAccountRequester;

    @Override
    protected void initViewModel() {

        states = getActivityScopeViewModel(MessageStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_nsgf_message, BR.vm, states)
                .addBindingParam(BR.click, new ClickProxy());
    }

    private ActivityNsgfMessageBinding mBinding;

    int[] mPageTitleBadgeList = new int[]{1, 1, 1};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (ActivityNsgfMessageBinding) getBinding();
        mBinding.titlebar.titleBarClear.setVisibility(View.VISIBLE);
        mBinding.titlebar.titleBarMenu.setVisibility(View.VISIBLE);
        mBinding.titlebar.titleBarClear.setOnClickListener(this::onClickSecurity);
        mBinding.titlebar.titleBarMenu.setOnClickListener(this::onClickSecurity);

        getLifecycle().addObserver(mAccountRequester);
        states.titleBar.set("消息推送");
        mBinding.viewPager.setOffscreenPageLimit(3);
        fragmentList.add(MessageFragment.newInstance(""));
        fragmentList.add(MessageFragment.newInstance("message.type.1"));
        fragmentList.add(MessageFragment.newInstance("message.type.2"));
        mPageTitleList = new String[]{"全部", "流程审批", "通知公告"};
        XFragmentAdapter adapter = new XFragmentAdapter(this, getSupportFragmentManager(), fragmentList, mPageTitleList);
        mBinding.viewPager.setAdapter(adapter);

        mAccountRequester.getMessageDetailResult().observe(this, responseStatusDataResult -> {

            if (responseStatusDataResult.getResponseStatus().isSuccess()) {
                if (200 == responseStatusDataResult.getResult().getResponseCode()) {

                    int[] mPageTitleBadgeList = new int[]{responseStatusDataResult.getResult().getData().getNoticeNum()
                            + responseStatusDataResult.getResult().getData().getApprovalNum(), responseStatusDataResult.getResult().getData().getApprovalNum(),
                            responseStatusDataResult.getResult().getData().getNoticeNum()};

                    for (int i = 0; i < mPageTitleBadgeList.length; i++) {

                        if (mPageTitleBadgeList[i] == 0) {
                            ((BadgePagerTitleView) (((CommonNavigator) mBinding.magicIndicator.getNavigator()).getPagerTitleView(i))).setBadgeView(null);
                        } else {
                            ((TextView) ((BadgePagerTitleView) (((CommonNavigator) mBinding.magicIndicator
                                    .getNavigator())
                                    .getPagerTitleView(i)))
                                    .getBadgeView())
                                    .setText(String.valueOf(mPageTitleBadgeList[i]));
                        }
                    }

                } else {
                    if (401 == responseStatusDataResult.getResult().getResponseCode()) {
                        UserInfo.getInstance().clearUserInfo();
                        finish();
                    }
                    ToastUtils.showShortToast(responseStatusDataResult.getResult().getMsg());
                }
            } else {
                ToastUtils.showLongToast(getErrorMsg(responseStatusDataResult.getResponseStatus().getE()));
            }
        });

        PublicMethodUtils.initMagicIndicatorBadgePager(mBinding.magicIndicator, mBinding.viewPager, mPageTitleList, mPageTitleBadgeList, MessageActivity.this);

        mAccountRequester.getSrc().observe(this, new Observer<DataResult<ResponseStatus<String>>>() {
            @Override
            public void onChanged(DataResult<ResponseStatus<String>> responseStatusDataResult) {

                if (responseStatusDataResult.getResponseStatus().isSuccess()) {
                    if (responseStatusDataResult.getResult().getResponseCode() == 200) {

                        ((BadgePagerTitleView) (((CommonNavigator) mBinding.magicIndicator.getNavigator()).getPagerTitleView(0))).setBadgeView(null);
                        ((BadgePagerTitleView) (((CommonNavigator) mBinding.magicIndicator.getNavigator()).getPagerTitleView(1))).setBadgeView(null);
                        ((BadgePagerTitleView) (((CommonNavigator) mBinding.magicIndicator.getNavigator()).getPagerTitleView(2))).setBadgeView(null);

                        ((MessageFragment) fragmentList.get(0)).notifyDataSetChanged();
                        ((MessageFragment) fragmentList.get(1)).notifyDataSetChanged();
                        ((MessageFragment) fragmentList.get(2)).notifyDataSetChanged();

                        EventMsg eventMsg = new EventMsg();
                        eventMsg.setMsg("warning");
                        RxBus.get().post(eventMsg);
                        EventBus.getDefault().post(eventMsg);

                    } else {
                        ToastUtils.showLongToast(responseStatusDataResult.getResult().getMsg());
                    }
                }
            }
        });

    }

    public static class MessageStates extends StateHolder {

        public final State<Boolean> loadingVisible = new State<>(false);
        public final State<Integer> searchVisible = new State<>(View.GONE);
        public final State<String> search = new State<>("");

    }


    public class ClickProxy {

        public void clear() {
            mAccountRequester.setClearMessage(mBinding.viewPager.getCurrentItem(), UserInfo.getInstance().getProjectCode());
        }

        public void search() {
            ((MessageFragment) fragmentList.get(0)).getDatas(states.search.get());
            ((MessageFragment) fragmentList.get(1)).getDatas(states.search.get());
            ((MessageFragment) fragmentList.get(2)).getDatas(states.search.get());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mAccountRequester.getUnreadCount(UserInfo.getInstance().getProjectCode(), false);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1001) {
                ((MessageFragment) fragmentList.get(0)).getDatas(data.getStringExtra("search"));
                ((MessageFragment) fragmentList.get(1)).getDatas(data.getStringExtra("search"));
                ((MessageFragment) fragmentList.get(2)).getDatas(data.getStringExtra("search"));
            }
        }
    }

    @Override
    protected void onClickSecurity(View v) {
        super.onClickSecurity(v);
        int id = v.getId();
        if (id == R.id.title_bar_clear) {
            mAccountRequester.setClearMessage(mBinding.viewPager.getCurrentItem(), UserInfo.getInstance().getProjectCode());
        } else if (id == R.id.title_bar_menu) {
            states.searchVisible.set(View.VISIBLE);
        }
    }

}
